<template>
  <div>
    <div>
      <we-button v-if="baseCode" @click="dialogFormVisible = true" type="primary" size="mini">
        <em class="el-icon-plus"></em> 新增
      </we-button>
      <we-button v-if="baseCode" @click="detailRow(currentRow)" type="primary" size="mini">
        <em class="el-icon-edit"></em> 修改
      </we-button>
      <we-button v-if="baseCode" @click="deleteRow"  type="primary" size="mini">
        <em class="el-icon-delete"></em> 删除
      </we-button>
      <span v-if="baseName">当前人员：【 {{baseName}} 】</span>
    </div>

    <!-- 表格 -->
    <el-table
      size="mini"
      height="116px"
      :header-cell-style="rowClass"
      :data="tableData"
      border
      highlight-current-row
      resizable
      ref="singleTable"
      @row-dblclick="detailRow"
      @current-change="handleCurrentChange"
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column
        prop="sort"
        :show-overflow-tooltip="true"
        width="150"
        label="职务排序"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        :show-overflow-tooltip="true"
        width="150"
        label="职务名称"
      >
      </el-table-column>
      <el-table-column
        prop="startTime"
        :show-overflow-tooltip="true"
        width="150"
        label="任职日期"
      >
      </el-table-column>
      <el-table-column
        prop="promotionTime"
        :show-overflow-tooltip="true"
        width="150"
        label="现级别提拔日期"
      >
      </el-table-column>
      <el-table-column
        prop="positionLevel_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="职务级别"
      >
      </el-table-column>
      <el-table-column
        prop="workUnit"
        :show-overflow-tooltip="true"
        width="150"
        label="任职单位"
      >
      </el-table-column>
      <el-table-column
        prop="appointNumber"
        :show-overflow-tooltip="true"
        width="150"
        label="任职文号"
      >
      </el-table-column>
      <el-table-column
        prop="postApprovalUnit"
        :show-overflow-tooltip="true"
        width="150"
        label="任职批准单位"
      >
      </el-table-column>
      <el-table-column
        prop="jobCategory_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="职务类别"
      >
      </el-table-column>
      <el-table-column
        prop="jobAttribute_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="职务属性"
      >
      </el-table-column>
      <el-table-column
        prop="modeAppointment_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="任职方式"
      >
      </el-table-column>
      <el-table-column
        prop="managementOrWork"
        :show-overflow-tooltip="true"
        width="150"
        label="主管或从事工作"
      >
      </el-table-column>
      <el-table-column
        prop="changeCategory_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="职务变动类别"
      >
      </el-table-column>
      <el-table-column
        prop="effectiveTime"
        :show-overflow-tooltip="true"
        width="150"
        label="职务生效日期"
      >
      </el-table-column>
      <el-table-column
        prop="appointmentReason_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="任职原因"
      >
      </el-table-column>
      <el-table-column
        prop="lowerLevelYear_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="在下一级任职年限"
      >
      </el-table-column>
      <el-table-column
        prop="positionClassification"
        :show-overflow-tooltip="true"
        width="150"
        label="职位分类"
      >
      </el-table-column>
      <el-table-column
        prop="currentPositionStatus_dictText"
        :show-overflow-tooltip="true"
        width="150"
        label="当前任职状态"
      >
      </el-table-column>
      <el-table-column
        prop="removalTime"
        :show-overflow-tooltip="true"
        width="150"
        label="免职日期"
      >
      </el-table-column>
      <el-table-column
        prop="previousLevelPromotionTime"
        :show-overflow-tooltip="true"
        width="150"
        label="上一级别提拔日期"
      >
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <we-button @click="detailRow(scope.row)" type="primary" size="mini"
            >详情</we-button
          >
          <we-button type="danger" @click="deleteRow(scope.row)" size="mini">删除</we-button>
        </template>
      </el-table-column> -->
    </el-table>
    <div class="table_tools">
      <we-pagination
        :total="pagination.total"
        :page="pagination.pageNum"
        :pageSize="pagination.pageSize"
        @currentChange="currentChange($event)"></we-pagination>
    </div>
    <!-- 表格 -->

    <!-- 新增弹窗 -->
    <el-dialog
      title="行政党派职务子集"
      @close="handleOffDialog"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        size="mini"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职务排序" prop="sort">
              <el-input
                class="inputW"
                v-model.number="ruleForm.sort"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务名称" prop="name">
              <el-input
                class="inputW"
                v-model="ruleForm.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任职日期" prop="startTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.startTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现级别提拔日期" prop="promotionTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.promotionTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职务级别" prop="positionLevel">
              <el-select
                class="inputW"
                v-model="ruleForm.positionLevel"
                placeholder="请选择活动区域"
                clearable
              >
              <el-option v-for="item in positionLevel" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任职单位" prop="workUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.workUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任职文号" prop="appointNumber">
              <el-input
                class="inputW"
                v-model="ruleForm.appointNumber"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任职批准单位" prop="postApprovalUnit">
              <el-input
                class="inputW"
                v-model="ruleForm.postApprovalUnit"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职务类别" prop="jobCategory">
              <el-select
                class="inputW"
                v-model="ruleForm.jobCategory"
                placeholder="请选择"
                clearable
              >
              <el-option v-for="item in jobCategory" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务属性" prop="jobAttribute">
              <el-cascader
                class="inputW"
                v-model="ruleForm.jobAttribute"
                :options="jobAttribute"
                :props="{ expandTrigger: 'hover' ,value:'uuid',label:'name',children: 'children'}"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任职方式" prop="modeAppointment">
              <el-select
                class="inputW"
                v-model="ruleForm.modeAppointment"
                placeholder="请选择活动区域"
                clearable
              >
              <el-option v-for="item in modeAppointment" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主管或从事工作" prop="managementOrWork">
              <el-input
                class="inputW"
                v-model="ruleForm.managementOrWork"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职务变动类别" prop="changeCategory">
              <el-select
                class="inputW"
                v-model="ruleForm.changeCategory"
                placeholder="请选择活动区域"
                clearable
              >
              <el-option v-for="item in changePosition" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务生效日期" prop="effectiveTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.effectiveTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任职原因" prop="appointmentReason">
              <el-select
                class="inputW"
                v-model="ruleForm.appointmentReason"
                placeholder="请选择活动区域"
                clearable
              >
                <el-option v-for="item in reasonsAppoiAntment" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="在下一级任职年限" prop="lowerLevelYear">
              <el-select
                class="inputW"
                v-model="ruleForm.lowerLevelYear"
                placeholder="请选择活动区域"
                clearable
              >
                <el-option v-for="item in nextLevel" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位分类" prop="positionClassification">
              <el-input
                class="inputW"
                v-model="ruleForm.positionClassification"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前任职状态" prop="currentPositionStatus">
              <el-select
                class="inputW"
                v-model="ruleForm.currentPositionStatus"
                placeholder="请选择活动区域"
                clearable
              >
                <el-option v-for="item in positionStatus" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="免职日期" prop="removalTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.removalTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上一级别提拔时间" prop="previousLevelPromotionTime">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.previousLevelPromotionTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
         <we-button size="mini" @click="handleOffDialog"
          >取 消</we-button
        >
        <we-button v-if="!isUpdate" size="mini" type="primary" @click="submitForm('ruleForm')"
          >新 增</we-button
        >
        <we-button v-if="isUpdate" size="mini" type="primary" @click="updateForm('ruleForm')"
          >修 改</we-button
        >
      </div>
    </el-dialog>
    <!-- 新增弹窗 -->
  </div>
</template>

<script>
import WeButton from '@/components/WeButton'
import WePagination from '@/components/WePagination'
import { parseTree } from '@/utils/util'
import { getAction, postAction, deleteAction, putAction } from '@/api/manage'
import {bus} from "@/utils/eventBus";
import {administrativePartyPosition} from "@/api/apiUrl";
export default {
  components: {
    WeButton,
    WePagination
  },
  data () {
    const checksort = (rule, value, callback) => {
      if (value) {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      isUpdate: false,
      pagination: {
        total: 10, // 总数据条数
        pageSize: 10, // 每页条数
        pageNum: 1 // 当前页
      }, // 列表分页数据
      tableData: [],
      dialogFormVisible: false,
      currentRow: null,
      ruleForm: {
        sort: '',
        name: '',
        startTime: '',
        promotionTime: '',
        positionLevel: '',
        workUnit: '',
        appointNumber: '',
        postApprovalUnit: '',
        jobCategory: '',
        jobAttribute: '',
        modeAppointment: '',
        managementOrWork: '',
        changeCategory: '',
        effectiveTime: '',
        appointmentReason: '',
        lowerLevelYear: '',
        positionClassification: '',
        currentPositionStatus: '',
        removalTime: '',
        previousLevelPromotionTime: '',
        uuidList:[],
      },
      rules: {
        sort: [{ validator: checksort, trigger: 'blur' }],
        name: [{ required: true, message: '请填写职务名称', trigger: 'blur' }],
        startTime: [
          { required: true, message: '请选择任职日期', trigger: 'change' }
        ],
        promotionTime: [
          {
            required: true,
            message: '请选择现级别提拔日期',
            trigger: 'change'
          }
        ],
        positionLevel: [
          { required: true, message: '请选择职务级别', trigger: 'change' }
        ],
        workUnit: [{ required: true, message: '请填写任职单位', trigger: 'blur' }],
        appointNumber: [{ required: true, message: '请填写任职文号', trigger: 'blur' }],
        jobAttribute: [
          { required: true, message: '请选择职务属性', trigger: 'change' }
        ],
        lowerLevelYear: [
          {
            required: true,
            message: '请选择在下一级任职年限',
            trigger: 'change'
          }
        ]
      },
      options: [],
      positionLevel: [], // 职务级别
      jobCategory: [], // 职务类别
      jobAttribute: [], // 职务属性
      modeAppointment: [], // 任职方式
      changePosition: [], // 职务变动类别
      reasonsAppoiAntment: [], // 任职原因
      nextLevel: [], // 在下一级任职年限
      positionStatus: [], // 当前任职状态
      baseCode: '',
      baseName: ''
    }
  },
  watch: {
    dialogFormVisible () {
      if (this.dialogFormVisible === false) {
        if (this.isUpdate) {
          setTimeout(() => {
            this.isUpdate = false
            this.clearForm()
            if (this.$refs.ruleForm !== undefined) {
              this.$refs.ruleForm.resetFields()
            }
          }, 500)
        }
        if (this.$store.state.administrative === true) {
          this.$store.commit('changeAdministrative', false)
        }
      }
    },
    '$store.state.baseCode'(newval) {
      this.baseCode  = newval
      this.getList ()
    },
    '$store.state.baseName'(newval) {
      this.baseName  = newval
    },
    '$store.state.administrative' (newval) {
      if (newval === true) {
        this.dialogFormVisible = true
        if (this.$store.state.updateSubset === true) {
          this.isUpdate = true
        } else {
          this.isUpdate = false
        }
        this.$store.commit('changeUpdateSubset', false)
        this.baseCodes = this.$store.state.baseCodes
        this.getPositionLevel()
        this.getJobCategory()
        this.getJobAttribute()
        this.getModeAppointment()
        this.getChangePosition()
        this.getReasonsAppoiAntment()
        this.getNextLevel()
        this.getPositionStatus()
      }
    }
  },
  methods: {
    clickSubset () {
      this.baseCode  = this.$store.state.baseCode
      this.getPositionLevel()
      this.getJobCategory()
      this.getJobAttribute()
      this.getModeAppointment()
      this.getChangePosition()
      this.getReasonsAppoiAntment()
      this.getNextLevel()
      this.getPositionStatus()
      this.getList()
    },
    batchAdd(data){
      this.dialogFormVisible = true
      this.ruleForm.uuidList = data
    },
    /*
     * 新增
     */
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = this.ruleForm
          data.jobAttribute = this.ruleForm.jobAttribute.pop()
          data.baseCode = this.baseCode
          data.sysOrgCode = '测试部门'
          data.createUser = '测试员'
          if (this.$store.state.administrative === true) {
            for (let i = 0; i < this.baseCodes.length; i++) {
              data.baseCode = this.baseCodes[i]
              postAction(administrativePartyPosition.add, data)
                .then(result => {
                  if (result.code === 200) {
                    this.dialogFormVisible = false
                    bus.$emit('handleDialog')
                    this.$message({
                      type: 'success',
                      message: '新增成功!'
                    })
                    this.clearForm()
                  } else {
                    this.$message({
                      type: 'warning',
                      message: result.msg
                    })
                  }
                })
            }
          } else {
            postAction(administrativePartyPosition.add, data)
              .then(result => {
                if (result.code === 200) {
                  this.getList()
                  this.dialogFormVisible = false
                  bus.$emit('handleDialog')
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  })
                } else {
                  this.$message({
                    type: 'warning',
                    message: result.msg
                  })
                }
              })
          }
        } else {
          return false
        }
      })
    },
    handleCurrentChange(val) {
        this.currentRow = val;
    },
    /**
     * 删除
     */
    deleteRow (row) {
      if(!this.currentRow){
        this.$message("请选择要删除的数据！")
        return
      }
      this.$confirm('是否要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          postAction(administrativePartyPosition.delete, { uuids: [this.currentRow.uuid] })
            .then((res) => {
              if (res.code === 200) {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              } else {
                this.$message({
                  type: 'warning',
                  message: res.msg
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    /**
     * 修改
     */
    updateForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm))
          if (typeof (this.ruleForm.jobAttribute) !== 'string') {
            data.jobAttribute = data.jobAttribute.pop()
          }
          data.updateUser = '修改员'
          postAction(administrativePartyPosition.update, data)
            .then(result => {
              if (result.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                bus.$emit('handleDialog')
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              } else {
                this.$message({
                  type: 'warning',
                  message: result.msg
                })
              }
            })
        } else {
          return false
        }
      })
    },
    handleOffDialog() {
      this.dialogFormVisible = false
      bus.$emit('handleDialog')
    },
    /**
     * 查询
     */
    getList () {
      let self = this
      postAction(administrativePartyPosition.administrativePartyPositionSearch, { baseCode: this.baseCode,size:this.pagination.pageSize, page:this.pagination.pageNum })
        .then(result => {
          if (result.code === 200) {
            if (!result.data.list.length && self.pagination.pageNum !== 1) {
              self.pagination.pageNum -= 1
              self.getList()
              return
            }
            self.pagination.total = result.data.total
            self.tableData = result.data.list
          }
        })
    },

    /**
     * 详情
     */
    detailRow (row) {
      if(!row){
        this.$message("请选择要编辑的数据！")
        return
      }
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.isUpdate = true
      this.dialogFormVisible = true
    },

    /**
     * 查询职务属性
     */
    getJobAttribute () {
        getAction('/opDictNew/findTreeByType?type=rs_ir')
        .then(result => {
          if (result.code === 200) {
            this.jobAttribute = result.data
          }
        })
    },

    /**
     * 获取职务级别字典
     */
    async getPositionLevel () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_zwcc')
      this.positionLevel = result.data
    },

    /**
     * 获取职务类别字典
     */
    async getJobCategory () {
      const result = await  getAction('/opDictNew/findTreeByType?type=rs_bq')
      this.jobCategory = result.data
    },

    /**
     * 获取任职方式字典
     */
    async getModeAppointment () {
      const result = await  getAction('/opDictNew/findTreeByType?type=rs_bl')
      this.modeAppointment = result.data
    },

    /**
     * 获取职务变动类型
     */
    async getChangePosition () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_bv')
      this.changePosition = result.data
    },

    /**
     * 获取任职原因字典
     */
    async getReasonsAppoiAntment () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_cq')
      this.reasonsAppoiAntment = result.data
    },

    /**
     * 获取在下一级任职年限字典
     */
    async getNextLevel () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_hu')
      this.nextLevel = result.data
    },

    /**
     * 获取在任职 状态
     */
    async getPositionStatus () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_bw')
      this.positionStatus = result.data
    },

    /**
     * 当前页改变
     */
    currentChange (event) {
      this.pagination.pageNum = event
      this.getList()
    },

    /**
     * 清除form
     */
    clearForm () {
      this.ruleForm = {
        sort: '',
        name: '',
        startTime: '',
        promotionTime: '',
        positionLevel: '',
        workUnit: '',
        appointNumber: '',
        postApprovalUnit: '',
        jobCategory: '',
        jobAttribute: '',
        modeAppointment: '',
        managementOrWork: '',
        changeCategory: '',
        effectiveTime: '',
        appointmentReason: '',
        lowerLevelYear: '',
        positionClassification: '',
        currentPositionStatus: '',
        removalTime: '',
        previousLevelPromotionTime: ''
      }
    },

    handleClose () {},
    handleChange () {},
    rowClass ({ row, rowIndex }) {
      return 'background:rgba(248, 248, 249, 1);color:#000;'
    }
  }
}
</script>

<style scoped>

.table_tools {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
